package ssm.blog.service.impl;

import org.springframework.stereotype.Service;
import ssm.blog.dao.AlbumMapper;
import ssm.blog.entity.Album;
import ssm.blog.entity.AlbumExample;
import ssm.blog.service.AlbumService;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;

/**
 * @program: lyon
 * @description: 相册服务层
 * @author: Lyon
 * @create: 2018-06-06 14:06
 **/
@Service
public class AlbumServiceImpl implements AlbumService {
    @Resource
    AlbumMapper mapper;
    @Override
    public int add(Album album) {
        album.setTitle("");
        album.setContent("");
        return mapper.insert(album);
    }

    @Override
    public List<Album> list() {
        AlbumExample example=new AlbumExample();
        example.setOrderByClause("id desc");
        return mapper.selectByExample(example);
    }

    @Override
    public List<Album> listByKeyword(String keyword) {
        AlbumExample example=new AlbumExample();
        example.setOrderByClause("id desc");
        example.createCriteria().andTitleLike("%"+keyword+"%");
        return mapper.selectByExample(example);
    }

    @Override
    public Album getById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public int update(Album album) {
        return mapper.updateByPrimaryKeySelective(album);
    }

    @Override
    public int deleByID(Integer id, HttpSession session) {
        Album album=getById(id);
        int result=mapper.deleteByPrimaryKey(id);
        if(result>0){
            File full=new File(session.getServletContext().getRealPath("/static/images/albums/fulls/"+album.getFull()));
            if(full.exists()){
                full.delete();
            }
            File thumb=new File(session.getServletContext().getRealPath("/static/images/albums/thumbs/"+album.getThumb()));
            if (thumb.exists()){
                thumb.delete();
            }
        }
        return result;
    }

    @Override
    public int deles(List<Integer> ids,HttpSession session) {
        int result=0;
        for(int i=0;i<ids.size();i++){
            result+=deleByID(ids.get(i),session);
        }
        return result;
    }

    @Override
    public int count() {
        AlbumExample example=new AlbumExample();
        return mapper.countByExample(example);
    }
}
